import confg from '../../utils/config';
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    imgurl: {
      type: Array//类型
    },
    limit:{
      type:Number,
      value:1
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    confg: confg,
    imageWidth: 0,
    imageHeight: 0
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
   * 删除图片
   */
  delimg(e) {
    let index = e.currentTarget.dataset.index;
    let arr =  this.data.imgurl;
    arr.splice(index, 1);
    this.setData({
      imgurl: arr
    })
    this.triggerEvent('imgurlEvent', { imgurl: arr });
  },
    /**
     * 图片上传服务器
     */
    imageUpdata(tempImg) {
      let arr = this.data.imgurl;
      wx.uploadFile({
        url: confg.base_url + '/api/v1/image/upload', // 仅为示例，非真实的接口地址
        filePath: tempImg,
        name: "file",
        formData: {},
        success: res => {
          let datas = JSON.parse(res.data)
          arr.push(datas.data)
          this.setData({
            imgurl:arr
          })
          this.triggerEvent('imgurlEvent', { imgurl: arr });
          wx.hideLoading()
        }
      });
    },
    /**
     * 点击按钮选择图片并开始压缩
     */
    takePhoto() {
      const limit = this.data.limit;
      if(limit > 1 && this.data.imgurl.length >= limit){
        wx.showModal({
          title: '提示',
          content: `图片不能超过${limit}张`,
          showCancel: false
        })
        return
      }
      const _this = this;
      wx.chooseImage({
        count: 1, //这个是上传的最大数量，默认为9
        sizeType: ['compressed'], //这个可以理解为上传的图片质量类型（官方给的），虽然没什么卵用，要不然还要我们自己写压缩做什么
        sourceType: ['album', 'camera'], //这个是图片来源，相册或者相机
        success: function (res) {
          wx.getSystemInfo({
            success: function (sys) { // 获取设备信息，开始压缩，并处理回调
              _this.getLessLimitSizeImage('attendCanvasId', res.tempFilePaths[0], 200, sys.screenWidth, (ss) => {
                _this.imageUpdata(ss)
              })
            }
          })
        }
      });
    },
    /**
     * 给的文件资源是否小于LimitSize （M）, 小于走lessCallBack， 大于走moreCallBack
     */
    imageSizeIsLessLimitSize(imagePath, limitSize, lessCallBack, moreCallBack) {
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      wx.getFileInfo({
        filePath: imagePath,
        success(res) {
          // console.log("压缩前图片大小:", res.size / 1024, 'kb');
          // console.log(res.size)
          if (res.size > 1024 * limitSize) {
            moreCallBack();
          } else {
            lessCallBack();
          }
        }
      })
    },
    /**
     * 获取小于限制大小的Image, limitSize默认为1M，递归调用。
     */
    getLessLimitSizeImage(canvasId, imagePath, limitSize = 1, drawWidth, callBack) {
      const _this = this;
      _this.imageSizeIsLessLimitSize(imagePath, limitSize,
        (lessRes) => {
          callBack(imagePath);
        },
        (moreRes) => {
          wx.getImageInfo({
            src: imagePath,
            success: function (imageInfo) {
              let maxSide = Math.max(imageInfo.width, imageInfo.height);
              let windowW = drawWidth; //画板的宽高默认是windowWidth
              let scale = 1;
              if (maxSide > windowW) {
                scale = windowW / maxSide;
              }
              let imageW = Math.floor(imageInfo.width * scale);
              let imageH = Math.floor(imageInfo.height * scale);
              // console.log('调用压缩', imageW, imageH);
              _this.setData({ // 设置画布的宽高
                imageWidth: imageW,
                imageHeight: imageH
              })
              _this.getCanvasImage(canvasId, imagePath, imageW, imageH,
                (pressImgPath) => {
                  _this.getLessLimitSizeImage(canvasId, pressImgPath, limitSize, drawWidth * 0.7, callBack);
                }
              );
            }
          })
        }
      )
    },
    /**
     * 获取画布图片 
     */
    getCanvasImage(canvasId, imagePath, imageW, imageH, getImgsuccess) {
      const _this = this;
      const ctx = wx.createCanvasContext(canvasId, this);
      ctx.drawImage(imagePath, 0, 0, imageW, imageH);
      ctx.draw();
      setTimeout(() => {
        wx.canvasToTempFilePath({
          canvasId: canvasId,
          x: 0,
          y: 0,
          width: imageW,
          height: imageH,
          quality: 1,
          success(res) {
            getImgsuccess(res.tempFilePath);
          },
          fail: function (err) {
            _this.getCanvasImage(canvasId, imagePath, imageW, imageH, getImgsuccess);
          }
        }, this);
      }, 300)
    }
  }
})